/*
-----------------------------------------------------------------------------
This source file is part of as4game
    (ActionScript For Game Engine)
For the latest info, see http://as4game.googlecode.com

Copyright (c) 2000-2011 Hproof Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
package org.as4game.render3d
{
	import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.display3D.textures.Texture;
	import flash.geom.Matrix3D;
	
	import mx.olap.aggregators.MaxAggregator;
	
	import org.as4game.resource.bitmap.Material;
	import org.as4game.resource.buffer.GeomBuffer;
	import org.as4game.resource.buffer.VertexBuffer;
	import org.as4game.resource.mesh.SubMesh;
	
	/**
	 * Pass 渲染通道, 是一次渲染的最小单元过程. 外部首先设置各共有属性, 然后调用 render 渲染
	 * 
	 */
	public class DefaultPass implements IPass
	{
		static private const MAX_BONE:uint = 40; 
			
		public var geomBuffer:GeomBuffer;				// 几何数据
		public var material:Material;					// 材质
		public var world:Matrix3D;						// 世界变化
		public var boneMatrices:Vector.<Matrix3D>;		// 骨骼矩阵数据, 全局骨骼ID
		public var fillColor:Vector.<Number>;			// 填充颜色, 如果材质为空, 则填充单色
		
		static private var boneVectors:Vector.<Number> = new Vector.<Number>( 16 * MAX_BONE );
		
		
		/**
		 * 是否有骨骼
		 */
		public function hasBone():Boolean{
//			return false;
			return geomBuffer.hasBone && boneMatrices && geomBuffer.bone_local2global.length < MAX_BONE;
		}
		
		private function trace(...args):void{
		}
		
		/**
		 * @inheritDoc
		 */
		public function get numTriangle():uint{
			return geomBuffer.index_buffer.indexCount / 3;
		}
		
		/**
		 * @inheritDoc
		 */
		public function render( context3d:Context3D, vp:Matrix3D ):void{
			
			// 设置常量
			var mvp:Matrix3D = world.clone();
			mvp.append( vp );
			
			context3d.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 0, mvp, true);		// [0] = mvp
//			mvp.copyRawDataTo( boneVectors, 0, true);
//			setBoneVectors( context3d );
			
			// 绘制
			context3d.drawTriangles( geomBuffer.index_buffer.getCardBuffer( context3d ) );
		}
		
		/**
		 * @inheritDoc
		 */
		public function activate( context3d:Context3D ):Boolean{
			
			// 检查是否有效
			if( 	!geomBuffer 
				|| 	!geomBuffer.index_buffer 
				|| 	!geomBuffer.position_buffer
				||	!geomBuffer.texture_buffer )
			{
				throw new Error("缺少必要的数据");
				return false;
			}
			
			// program
			var program:Program3D = _buildProgram( context3d );
			if(! program ) return false;
			
			context3d.setProgram( program );
			
			// va
			var vb:VertexBuffer;
			vb = geomBuffer.position_buffer;
			context3d.setVertexBufferAt( 0, vb.getCardBuffer( context3d ), 0, vb.vertexFormat );	// va0 = position
			
			vb = geomBuffer.texture_buffer;
			context3d.setVertexBufferAt( 1, vb.getCardBuffer( context3d ), 0, vb.vertexFormat );	// va1 = texture
			
			if( hasBone() ){
				vb = geomBuffer.bone_index_buffer;
				context3d.setVertexBufferAt( 2, vb.getCardBuffer( context3d ), 0, vb.vertexFormat );	// va2 = bone_index
//				
				vb = geomBuffer.bone_weight_buffer;
				context3d.setVertexBufferAt( 3, vb.getCardBuffer( context3d ), 0, vb.vertexFormat );	// va3 = bone_weight
				
				var local2global:Vector.<uint> = geomBuffer.bone_local2global;
				if( local2global.length > MAX_BONE ){
					deactivate( context3d ); // 骨骼数量有限制
					return false;
				}
				
				setBoneVectors( context3d );
			}
			
			// texture & color
			if( material ){
				context3d.setTextureAt(0, material.getTexture( context3d ) );							// fs0 = texture
			}
			else{
				fillColor = fillColor || Vector.<Number>([1, 1, 1, 1]);
				context3d.setProgramConstantsFromVector( Context3DProgramType.FRAGMENT, 0, fillColor,  1 );	// fc0 = fillColor
			}
			
			//
			return true;
		}
		
		/**
		 * @inheritDoc
		 */
		public function deactivate( context3d:Context3D ):void{
			
			// 清理渲染状态
			context3d.setProgram( null );
			
			context3d.setVertexBufferAt( 0, null);
			context3d.setVertexBufferAt( 1, null);
			if( hasBone() ){
				context3d.setVertexBufferAt( 2, null);
				context3d.setVertexBufferAt( 3, null);
//				for(var i:int=0; i<boneMatrices.length; i++){
//					context3d.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, i+16, null);
//				}
			}
			
			if( material ){
				context3d.setTextureAt(0, null);
			}
		}
		
		// 设置骨骼矩阵
		private function setBoneVectors( context3d:Context3D ):void{
			var local2global:Vector.<uint> = geomBuffer.bone_local2global;
			for(var i:int=0; i<local2global.length; i++){
				var global_id:int = local2global[ i ];
				var matrix:Matrix3D = boneMatrices[ global_id ];
				var start:int = i * 12 + 16;
				matrix.copyRawDataTo( boneVectors, start, true);
				
			}
			context3d.setProgramConstantsFromVector( Context3DProgramType.VERTEX, 0, boneVectors, 3*local2global.length + 4);
		}
		
		// =====================================================================
		// shader 代码构造
		
		/**
		 * 构造渲染代码
		 */
		private function _buildProgram( context3d:Context3D ):Program3D{
			
			var key:String = _getProgramKey();
			var program:Program3D = programPool[ key ];
			if( ! program ){
				program = _buildProgramImp( context3d );
				programPool[ key ] = program;
			}
			return program;
		}
		static private var programPool:Object = {};
		
		
		/**
		 * 建立 shader
		 * <li> vc0 	-- MVP 矩阵
		 * <Li> vc4		-- 骨骼矩阵开始
		 * <li> va0		-- 顶点坐标
		 * <li> va1		-- 纹理坐标
		 * <li> va2		-- 骨骼索引(可选)
		 * <li> va3		-- 骨骼权值(可选)
		 * <li> fs0		-- 纹理
		 */
		private function _buildProgramImp( context3d:Context3D ):Program3D {
			
			//
			var vasm:String = "";

			// 骨骼变化, 坐标输出到 vt0
			if( hasBone() ){
				// vt0 是最终结果, vt1-vt4 是临时寄存器
				var bpv:int = geomBuffer.bone_max_per_vertex;
				if( bpv > 0 ) vasm += "" +
//					"m44 vt1, va0, vc[va2.x+16]\n" +
					"dp4 vt1.x, va0, vc[va2.x+4]\n" +
					"dp4 vt1.y, va0, vc[va2.x+5]\n" +
					"dp4 vt1.z, va0, vc[va2.x+6]\n" +
					"mov vt1.w, va0.w\n"+
					"mul vt1, vt1, va3.x\n" +
					"mov vt0, vt1\n" +
					"";
				if( bpv > 1 ) vasm += "" +
//					"m44 vt2, va0, vc[va2.y+16]\n" +
					"dp4 vt2.x, va0, vc[va2.y+4]\n" +
					"dp4 vt2.y, va0, vc[va2.y+5]\n" +
					"dp4 vt2.z, va0, vc[va2.y+6]\n" +
					"mov vt2.w, va0.w\n"+
					"mul vt2, vt2, va3.y\n" +
					"add vt0, vt0, vt2\n" +
					"";
				if( bpv > 2 ) vasm += "" +
//					"m44 vt3, va0, vc[va2.z+16]\n" +
					"dp4 vt3.x, va0, vc[va2.z+4]\n" +
					"dp4 vt3.y, va0, vc[va2.z+5]\n" +
					"dp4 vt3.z, va0, vc[va2.z+6]\n" +
					"mov vt3.w, va0.w\n"+
					"mul vt3, vt3, va3.z\n" +
					"add vt0, vt0, vt3\n" +
					"";
				if( bpv > 3 ) vasm += "" +
//					"m44 vt4, va0, vc[va2.w+16]\n" +
					"dp4 vt4.x, va0, vc[va2.w+4]\n" +
					"dp4 vt4.y, va0, vc[va2.w+5]\n" +
					"dp4 vt4.z, va0, vc[va2.w+6]\n" +
					"mov vt4.w, va0.w\n"+
					"mul vt4, vt4, va3.w\n" +
					"add vt0, vt0, vt4\n" +
					"";
				vasm += "mov vt0.w, va0.w\n";
			}
			else{
				vasm += "mov vt0, va0\n" +
					"";
			}
			
			// 输出坐标
			vasm += "m44 op, vt0, vc0\n";
			
			// 保存纹理到 v0
			vasm += "mov v0, va1\n";
			
			
			// 像素着色器
			var fasm:String = "";
			
			if( material ){
				fasm += "" +
					"mov ft0, v0\n"+
					"tex ft1, ft0, fs0 <2d,clamp,linear>\n"+		// 简单取纹理	
					"mov oc, ft1\n" +
					"";
			}
			else{
				fasm += "" +
					"mov oc, fc0\n";					// 填充颜色
			}
			
			//
			trace( vasm );
			trace( fasm );
			return makeShader( vasm, fasm, context3d );
		}
		
		/**
		 * 获取着色器代码的 key
		 */
		private function _getProgramKey():String{
			var arr:Array = [];
			
			with( geomBuffer ){
//				arr.push( position_buffer.vertexSize );			// 坐标格式
//				arr.push( texture_buffer? 1: 0);
//				arr.push( normal_buffer? 1: 0);
				arr.push( hasBone ? 1: 0);						// 是否有骨骼
				arr.push( bone_max_per_vertex);					// 骨骼数量
				arr.push( material? 1: 0);						// 是否有纹理
			}
			
			var key:String = arr.join(",");
			return key;
		}
		
		
		/**
		 * 编译 shader 代码
		 */
		static public function makeShader( vertexSource:String, fragmentSource:String, context3d:Context3D ):Program3D{
			
			var vasm: AGALMiniAssembler = new AGALMiniAssembler();
			vasm.assemble( Context3DProgramType.VERTEX, vertexSource );
			
			var fasm: AGALMiniAssembler= new AGALMiniAssembler(); 
			fasm.assemble( Context3DProgramType.FRAGMENT, fragmentSource );
			
			var program:Program3D = context3d.createProgram();
			program.upload( vasm.agalcode, fasm.agalcode );
			
			return program;
		}
	}
}